import React, { useState, useEffect, useContext } from 'react';
import { Select, Input } from '@supcon/supcon-5t-design';
import { SearchOutlined } from '@ant-design/icons';
import styles from './index.module.less';
import { AnomalyContext } from '@/pages/BigScreen/context/AnomalyContext';

interface AnomalyFilterProps {
  onFilter: (filter: string, groupType?: string) => void;
  onSearch: (keyword: string) => void;
  onInputChange: (keyword: string) => void;
  filterValue?: string;  // 添加外部传入的筛选值
  groupValue?: string;   // 添加外部传入的分组值
  searchValue?: string;  // 添加外部传入的搜索值
}

const AnomalyFilter: React.FC<AnomalyFilterProps> = ({
  onFilter,
  onSearch,
  onInputChange,
  filterValue: externalFilterValue,
  groupValue: externalGroupValue,
  searchValue: externalSearchValue
}) => {
  // 获取上下文中的 groupTagMap
  const { groupTagMap } = useContext(AnomalyContext);
  
  const [filterValue, setFilterValue] = useState<string>(externalFilterValue || 'all');
  const [groupValue, setGroupValue] = useState<string>(externalGroupValue || '');
  const [searchValue, setSearchValue] = useState<string>(externalSearchValue || '');

  // 当外部值变化时同步更新内部状态
  useEffect(() => {
    if (externalFilterValue !== undefined && externalFilterValue !== filterValue) {
      setFilterValue(externalFilterValue);
    }
  }, [externalFilterValue]);

  useEffect(() => {
    if (externalGroupValue !== undefined && externalGroupValue !== groupValue) {
      setGroupValue(externalGroupValue);
    }
  }, [externalGroupValue]);

  useEffect(() => {
    if (externalSearchValue !== undefined && externalSearchValue !== searchValue) {
      setSearchValue(externalSearchValue);
    }
  }, [externalSearchValue]);

  const handleFilterChange = (value: string) => {
    setFilterValue(value);
    onFilter(value, groupValue);
  };

  const handleGroupChange = (value: string) => {
    setGroupValue(value);
    onFilter(filterValue, value);
  };

  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setSearchValue(value);
    onInputChange(value);
  };

  const handleSearchSubmit = () => {
    onSearch(searchValue);
  };

  // 根据 groupTagMap 生成分组选项
  const getGroupOptions = () => {
    // 默认添加"全部"选项
    const defaultOption = [{ value: '', label: '全部' }];
    
    // 如果 groupTagMap 是数组，则处理数据
    if (Array.isArray(groupTagMap) && groupTagMap.length > 0) {
      // 去重：同一个 groupType 可能对应多个 evaluationItemName
      const uniqueGroups = new Map();
      
      groupTagMap.forEach(item => {
        if (item.groupType && !uniqueGroups.has(String(item.groupType))) {
          // 使用 groupType 作为键，确保唯一性
          uniqueGroups.set(String(item.groupType), {
            value: String(item.groupType),
            label: item.groupTypeName || item.evaluationItemName || String(item.groupType)
          });
        }
      });
      
      // 将 Map 转换为数组
      const options = Array.from(uniqueGroups.values());
      
      // 返回合并后的选项
      return [...defaultOption, ...options];
    }
    return [
      { value: '', label: '全部' }
    ];
  };

  return (
    <div className={styles['filter-container']}>
      <div className={styles['filter-group']}>
        <div className={styles['filter-label']}>分组:</div>
        <div className={styles['filter-selector']}>
          <Select
            value={groupValue}
            style={{ width: 110 }}
            onChange={handleGroupChange}
            options={getGroupOptions()}
          />
        </div>
      </div>
      <div className={styles['filter-group']}>
        <div className={styles['filter-label']}>状态:</div>
        <div className={styles['filter-selector']}>
          <Select
            value={filterValue}
            style={{ width: 80 }}
            onChange={handleFilterChange}
            options={[
              { value: 'all', label: '全部' },
              { value: 'red', label: '报警' },
              { value: 'yellow', label: '预警' },
              { value: 'green', label: '正常' }
            ]}
          />
        </div>
      </div>
      <div className={styles['search-box']}>
        <Input
          placeholder="输入位号描述搜索"
          value={searchValue}
          onChange={handleSearch}
          onPressEnter={handleSearchSubmit}
          allowClear
          suffix={
            <SearchOutlined 
              onClick={handleSearchSubmit}
              className={styles['search-icon']}
            />
          }
        />
      </div>
    </div>
  );
};

export default AnomalyFilter; 